package com.demo.java.OD151_200.OD199;

import java.util.*;


/**
 * @author bug菌
 * @Source 公众号：猿圈奇妙屋
 * @des： 【单核CPU任务调度、任务调度本】问题
 * @url： https://blog.csdn.net/weixin_43970743/article/details/145890005
 */
public class OdMain {

    // 定义任务类
    static class Task implements Comparable<Task> {
        int id;
        int priority;
        int duration;
        int arriveTime;

        Task(int id, int priority, int duration, int arriveTime) {
            this.id = id;
            this.priority = priority;
            this.duration = duration;
            this.arriveTime = arriveTime;
        }

        @Override
        public int compareTo(Task o) {
            if (this.priority == o.priority) {
                return this.arriveTime - o.arriveTime;  // 如果优先级相同，按到达时间排序
            }
            return o.priority - this.priority;  // 优先级高的任务优先执行
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();  // 任务数

        // 创建优先队列来按优先级和到达时间排序任务
        PriorityQueue<Task> taskQueue = new PriorityQueue<>((t1, t2) -> {
            if (t1.priority == t2.priority) {
                return t1.arriveTime - t2.arriveTime;  // 优先级相同，按到达时间排序
            }
            return t2.priority - t1.priority;  // 优先级高的任务先执行
        });

        // 存储任务信息
        List<Task> tasks = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int id = scanner.nextInt();
            int priority = scanner.nextInt();
            int duration = scanner.nextInt();
            int arriveTime = scanner.nextInt();
            tasks.add(new Task(id, priority, duration, arriveTime));
        }

        // 当前时间和任务索引
        int currentTime = 0;
        int taskIndex = 0;

        // 处理任务
        while (taskIndex < n || !taskQueue.isEmpty()) {
            // 先将到达的任务放入队列
            while (taskIndex < n && tasks.get(taskIndex).arriveTime <= currentTime) {
                taskQueue.add(tasks.get(taskIndex));
                taskIndex++;
            }

            // 如果有任务可以执行，取出队列中的任务并执行
            if (!taskQueue.isEmpty()) {
                Task currentTask = taskQueue.poll();
                currentTime += currentTask.duration;
                System.out.println(currentTask.id + " " + currentTime);  // 输出任务ID和完成时间
            } else {
                // 如果没有任务可以执行，则时间跳到下一个任务的到达时间
                currentTime = tasks.get(taskIndex).arriveTime;
            }
        }
    }
}